package com.sun.temp.controller;
import com.sun.temp.bean.*;
import com.sun.temp.common.result.Result;
import com.sun.temp.mapper.mapper2.PrdBcdQaPlanresultDao;
import com.sun.temp.mapper.mapper2.PrdBcdQaPlanresultExDao;
import com.sun.temp.mapper.mapper2.QaRpaCureInspDao;
import com.sun.temp.mapper.mapper3.QakansaDao;
import com.sun.temp.service.QaRpaCureInspService;
import com.sun.temp.service.WeightService2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.geometry.partitioning.BSPTree;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.DecimalFormat;
import java.util.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;

/**
 * <p>
 * $ {description}
 * </p>
 *
 * @author: Mr.Wang
 * @create: 2025-08-25 14:34
 **/
@Slf4j
@RestController
@RequestMapping("/weight")
public class WeightController {
    private static double TARGET_TEMPERATURE = 100.0;

    @Autowired
    private WeightService2 weightService2;

    @Resource
    private QakansaDao qakansaDao;

    @Autowired
    private QaRpaCureInspService qaRpaCureInspService;

    @Resource
    private QaRpaCureInspDao qaRpaCureInspDao;

    @Resource
    private PrdBcdQaPlanresultDao resultDao;
    @Resource
    private PrdBcdQaPlanresultExDao resultExDao;

    /**
     * 根据等级拿比重
     * @param grade
     * @return
     */
    @GetMapping("/getSgByGrade")
    public Result getSgByGrade(@RequestParam String grade) {
        return Result.success(weightService2.getSgByGrade(grade));
    }

    /**
     * 根据等级拿比重--获取的是list
     * @param grade
     * @return
     */
    @GetMapping("/getSgListByGrade")
    public Result getSgListByGrade(@RequestParam String grade) {
        List<WeightBean2> list = weightService2.getSgListByGrade(grade);
        WeightBean2 weightBean2 = null;
        if(list != null && list.size() > 0){
            weightBean2 = list.get(0);
        }
        return Result.success(weightBean2);
    }

    @GetMapping("/getAllGrade")
    public Result getAllGrade() {
        return Result.success(weightService2.getAllGrade());
    }

//    @GetMapping("/deleteGrade")
//    public Result deleteGrade(@RequestParam String batch) {
//        return Result.success(weightService2.removeByBatch(batch));
//    }

    @GetMapping("/getAllInspData")
    public Result getAllInspData() {
        return Result.success(qaRpaCureInspService.getAllInspData());
    }

//    @GetMapping("/deleteInspData")
//    public Result deleteInspData(@RequestParam String batchNo) {
//        return Result.success(qaRpaCureInspService.deleteInspData(batchNo));
//    }

    /**
     * 去QA_RPA_CURE_INSP查找有没有当前编号100(101)、等级、批次的实验数据,判断有没有做过实验
     * @param
     * @return
     */
    @GetMapping("/getInspData")
    public Result getInspData(@RequestParam String grade,@RequestParam String batch) {
        List<QaRpaCureInspBean> list = qaRpaCureInspService.getInspData(batch);
        return Result.success(list);
    }

    /**
     * 根据批次拿实验编号100、101
     * @param batchNo
     * @return
     */
    @GetMapping("/getQakansaByBatch")
    public Result getQakansaByBatch(@RequestParam String batchNo) {
        List<Qakansa> list = qakansaDao.getByBatch(batchNo);
        return Result.success(list);
    }

    /**
     * oracle保存等级、比重、重量
     */
    @PostMapping("/saveGradeWeightSg")
    public Result saveGradeWeightSg(@RequestBody WeightBean2 weight) {
        return Result.success(weightService2.saveWeight(weight));
    }

    /**
     * 点击屏幕并截屏,找坐标100秒
     * @return
     * @throws Exception
     */
    @GetMapping("/rpaOcrClick100")
    public Result rpaOcrClick100() throws Exception{
        int positionX = 407;
        int positionY = 578;
        String result = "";
        System.out.println("[找100秒坐标]开始时间>>>>>>>>>>>>>>>："+new Date());
        while(true) {
            result = doClickScreen(positionX, positionY);
            System.out.println("[找100秒坐标]识别result>>>>>>>>>：" + result);

            if(result.contains("识别失败")){
                System.out.println("[找100秒坐标]识别失败>>>>>>>>>>>>>>>");
            }else {
                if(result.contains("Text not recognized>>>>>>>")){
                    System.out.println("[找100秒坐标]未识别到文字>>>>>>>>>>>>>>>");
                } else {
                    System.out.println("[找100秒坐标]识别到文字>>>>>>>>>>>>>>>"+result);
                    if(result.contains("秒") || result.contains("kg")  || result.contains("Kg") || result.contains("gf") || result.contains("kgf") || result.contains("cm")) {
                        System.out.println("[找100秒坐标]找到跳出>>>>>>>>："+new Date());
                        break;
                    }
                }
            }
            if(positionY >= 500) {
                positionY -= 2;
                System.out.println("[找100秒坐标]继续找>>>>>>>>>>>>>>>："+positionY+">"+(new Date().toString()));
            } else {
                // 处理坐标越界情况
                System.out.println("[找100秒坐标]坐标越界>>>>>>>>>>>>>>>");
                break; 
            }
        }
        System.out.println("[找100秒坐标]最终获取结果：" + result);
        return Result.success(result);
    }
    
    public String doClickScreen(int positionX,int positionY) throws Exception{
        clickScreen(String.valueOf(positionX),String.valueOf(positionY));
        String ocrResult = cutScreen(String.valueOf(positionX),String.valueOf(positionY));
        return ocrResult;
    }
    
    /**
     * 点击屏幕，找坐标
     * @return
     * @throws Exception
     */
    @GetMapping("/clickScreen")
    public Result clickScreen(String positionX,String positionY) throws Exception{

        // Python脚本路径及参数
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\clickCoordinates.py";

        ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript, positionX, positionY);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (exitCode == 0) {
//                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
            } else {
//                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
            }

            process.destroy();
        }
        return Result.success();
    }

    /**
     * 截图
     * @return
     * @throws Exception
     */
//    @GetMapping("/cutScreen")
    public String cutScreen(String positionX,String positionY) throws Exception{
//        System.setProperty("file.encoding", "UTF-8");
//        PrintStream out = new PrintStream(System.out, true, "UTF-8");
//        System.setOut(out);

        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\curelastio-test4.py";

        ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript, positionX, positionY);
        Process process = processBuilder.start();

//        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            process.destroy();
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
                return output.toString();
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
                return "识别失败";
            }

//            process.destroy();
        }
    }

    /**
     * 点击屏幕并截屏,找坐标300秒
     * @return
     * @throws Exception
     */
    @GetMapping("/rpaOcrClick300")
    public Result rpaOcrClick300() throws Exception{
        int positionX = 1041;
        int positionY = 548;
        String result = "";
        System.out.println("[找300秒坐标]开始时间>>>>>>>>>>>>>>>："+new Date());
        while(true) {
            result = doClickScreen(positionX, positionY);
            System.out.println("[找300秒坐标]识别result>>>>>>>>>：" + result);

            if(result.contains("识别失败")){
                System.out.println("[找300秒坐标]识别失败>>>>>>>>>>>>>>>");
            }else {
                if(result.contains("Text not recognized>>>>>>>")){
                    System.out.println("[找300秒坐标]未识别到文字>>>>>>>>>>>>>>>");
                } else {
                    System.out.println("[找300秒坐标]识别到文字>>>>>>>>>>>>>>>"+result);
                    if(result.contains("秒") || result.contains("kg")  || result.contains("Kg") || result.contains("gf") || result.contains("kgf") || result.contains("cm")) {
                    System.out.println("[找300秒坐标]找到跳出>>>>>>>>："+new Date());
                    break;
                    }
                }
            }
            if(positionY >= 400) {
                positionY -= 8;
                System.out.println("[找300秒坐标]继续找>>>>>>>>>>>>>>>："+positionY+">"+(new Date().toString()));
            } else {
                // 处理坐标越界情况
                System.out.println("[找300秒坐标]坐标越界>>>>>>>>>>>>>>>");
                break;
            }
        }
        System.out.println("[找300秒坐标]最终获取结果：" + result);
        return Result.success(result);
    }

    /**
     * 点击屏幕并截屏,找坐标60秒
     * @return
     * @throws Exception
     */
    @GetMapping("/rpaOcrClick60")
    public Result rpaOcrClick60() throws Exception{
        int positionX = 283;
        int positionY = 596;
        String result = "";
        System.out.println("[找60秒坐标]开始时间>>>>>>>>>>>>>>>："+new Date());
        while(true) {
            result = doClickScreen(positionX, positionY);
            System.out.println("[找60秒坐标]识别result>>>>>>>>>：" + result);

            if(result.contains("识别失败")){
                System.out.println("[找60秒坐标]识别失败>>>>>>>>>>>>>>>");
            }else {
                if(result.contains("Text not recognized>>>>>>>")){
                    System.out.println("[找60秒坐标]未识别到文字>>>>>>>>>>>>>>>");
                } else {
                    System.out.println("[找60秒坐标]识别到文字>>>>>>>>>>>>>>>"+result);
                    if(result.contains("秒") || result.contains("kg")  || result.contains("Kg") || result.contains("gf") || result.contains("kgf") || result.contains("cm")) {
                        System.out.println("[找60秒坐标]找到跳出>>>>>>>>："+new Date());
                        break;
                    }
                }
            }
            if(positionY >= 400) {
                positionY -= 8;
                System.out.println("[找60秒坐标]继续找>>>>>>>>>>>>>>>："+positionY+">"+(new Date().toString()));
            } else {
                // 处理坐标越界情况
                System.out.println("[找60秒坐标]坐标越界>>>>>>>>>>>>>>>");
                break;
            }
        }
        System.out.println("[找60秒坐标]最终获取结果：" + result);
        return Result.success(result);
    }


    /**
     * 点击屏幕并截屏,找坐标90秒
     * @return
     * @throws Exception
     */
    @GetMapping("/rpaOcrClick90")
    public Result rpaOcrClick90() throws Exception{
        int positionX = 378;
        int positionY = 578;
        String result = "";
        System.out.println("[找90秒坐标]开始时间>>>>>>>>>>>>>>>："+new Date());
        while(true) {
            result = doClickScreen(positionX, positionY);
            System.out.println("[找90秒坐标]识别result>>>>>>>>>：" + result);

            if(result.contains("识别失败")){
                System.out.println("[找90秒坐标]识别失败>>>>>>>>>>>>>>>");
            }else {
                if(result.contains("Text not recognized>>>>>>>")){
                    System.out.println("[找90秒坐标]未识别到文字>>>>>>>>>>>>>>>");
                } else {
                    System.out.println("[找90秒坐标]识别到文字>>>>>>>>>>>>>>>"+result);
                    if(result.contains("秒") || result.contains("kg")  || result.contains("Kg") || result.contains("gf") || result.contains("kgf") || result.contains("cm")) {
                        System.out.println("[找90秒坐标]找到跳出>>>>>>>>："+new Date());
                        break;
                    }
                }
            }
            if(positionY >= 400) {
                positionY -= 8;
                System.out.println("[找90秒坐标]继续找>>>>>>>>>>>>>>>："+positionY+">"+(new Date().toString()));
            } else {
                // 处理坐标越界情况
                System.out.println("[找90秒坐标]坐标越界>>>>>>>>>>>>>>>");
                break;
            }
        }
        System.out.println("[找90秒坐标]最终获取结果：" + result);
        return Result.success(result);
    }


    /**
     * 找到坐标后，点击终了-终了关闭窗口
     * @return
     * @throws Exception
     */
    @GetMapping("/zhongliao")
    public Result zhongliao() throws Exception {

        // Python脚本路径及参数
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\zhongliao.py";
        pythnExcute(pythonScript);
        return Result.success();
    }


    /**
     * 测定表示--显示曲线
     * @return
     * @throws Exception
     */
    @GetMapping("/cedingShow")
    public Result cedingShow() throws Exception {

        // Python脚本路径及参数
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\cedingShow.py";
        pythnExcute(pythonScript);
        return Result.success();
    }

    /**
     * 实验5分钟后，会自动关闭测定中窗口，我需要关闭测定依赖登录窗口
     * @return
     * @throws Exception
     */
    @GetMapping("/cedingyilaidenglu")
    public Result cedingyilaidenglu() throws Exception {

        // Python脚本路径及参数
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\cedingyilaidenglu.py";
        pythnExcute(pythonScript);
        return Result.success();
    }

    /**
     * 检索
     * @return
     * @throws Exception
     */
    @GetMapping("/jiansuo")
    public Result jiansuo() throws Exception {

        // Python脚本路径及参数
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\jiansuo.py";
        pythnExcute(pythonScript);
        return Result.success();
    }


    /**
     * 测定--输一条数据
     * @return
     * @throws Exception
     */
    @GetMapping("/ceding")
    public Result ceding(@RequestParam String num,@RequestParam String grade, @RequestParam String batch) throws Exception {

        // Python脚本路径及参数
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\ceding.py";
        ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript,num, grade, batch);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
            }

            process.destroy();
        }
        return Result.success();
    }

    /**
     * 测定--输两条数据
     * @return
     * @throws Exception
     */
    @GetMapping("/ceding2")
    public Result ceding2(@RequestParam String num1,@RequestParam String num2,@RequestParam String grade, @RequestParam String batch) throws Exception {

        // Python脚本路径及参数
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\ceding2.py";
        ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript, num1,num2,grade, batch);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
            }

            process.destroy();
        }
        return Result.success();
    }

    public void pythnExcute(String path) throws Exception{
        ProcessBuilder processBuilder = new ProcessBuilder("python", path);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
            }

            process.destroy();
        }
    }

    @GetMapping("/findClosestData")
    public Result findClosestData(@RequestParam String grade){

        String temp60 = findClosestDataByGradeAndTemperature(grade,60.0);
        String temp90 = findClosestDataByGradeAndTemperature(grade,90.0);
        String temp100 = findClosestDataByGradeAndTemperature(grade,100.0);
        String temp120 = findClosestDataByGradeAndTemperature(grade,120.0);
        String temp150 = findClosestDataByGradeAndTemperature(grade,150.0);
        String temp240 = findClosestDataByGradeAndTemperature(grade,240.0);
        String temp300 = findClosestDataByGradeAndTemperature(grade,300.0);
        List<String> list = new ArrayList<>();
        list.add(temp60);
        list.add(temp90);
        list.add(temp100);
        list.add(temp120);
        list.add(temp150);
        list.add(temp240);
        list.add(temp300);
       return Result.success(list);
    }

    public String findClosestDataByGradeAndTemperature(@RequestParam String grade,@RequestParam double temperature){
        // 直接设置文件路径为用户提供的D:\tmp\test.CSV
//        String filePath = "D:\\curelasto\\tmp\\test.CSV";
        String filePath = "D:\\USERS\\01001433\\DESKTOP\\"+grade+".CSV";
        TARGET_TEMPERATURE = temperature;
        String resut = "";

        // 用于存储离目标温度最近的行信息
        String nearestRow = null;
        int nearestRowNumber = -1;
        double nearestTemperature = 0;
        double minDifference = Double.MAX_VALUE;

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            int rowNumber = 1;

            // 读取表头（第一行）
            if ((line = reader.readLine()) != null) {
                System.out.println("表头: " + line);
                rowNumber++;
            }

            // 遍历每一行数据
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) {
                    rowNumber++;
                    continue; // 跳过空行
                }

                // 优先尝试用逗号分割，因为用户的文件样例显示是逗号分隔的
                String[] parts = line.trim().split(",");

                // 添加调试信息，显示当前行的分割结果
//                System.out.println("行号: " + rowNumber + ", 使用逗号分割后的元素数量: " + parts.length);

                // 如果逗号分割后元素数量较少，尝试用空格分割
                if (parts.length < 2) {
                    parts = Pattern.compile("\\s+").split(line.trim());
                    System.out.println("尝试用空格分割后的元素数量: " + parts.length);
                }

                // 即使元素数量少于5，也尝试处理，提高代码的兼容性
                if (parts.length >= 1) { // 至少有一列数据
                    try {
                        // 只使用第一列作为温度数据
                        boolean foundTemperature = false;
                        try {
                            // 第一列的索引是0
                            double temp = Double.parseDouble(parts[0].trim());
                            // 不再检查温度合理性，直接处理
                            double diff = Math.abs(temp - TARGET_TEMPERATURE);
                            if (diff < minDifference) {
                                minDifference = diff;
                                nearestRow = line;
                                nearestRowNumber = rowNumber;
                                nearestTemperature = temp;
//                                System.out.println("找到更接近的温度值: " + temp + "°C (行号: " + rowNumber + ", 第一列)");
                            }
                            foundTemperature = true;
                        } catch (NumberFormatException ignored) {
                            System.out.println("警告: 第" + rowNumber + "行第一列不是有效的温度值");
                        }
                        if (!foundTemperature) {
                            System.out.println("警告: 第" + rowNumber + "行未找到有效的温度值");
                        }
                    } catch (Exception e) {
                        System.out.println("处理第" + rowNumber + "行时出错: " + e.getMessage());
                    }
                }
                rowNumber++;
            }

            // 输出结果
            if (nearestRow != null) {
                System.out.println("\n找到离 " + TARGET_TEMPERATURE + "°C 最近的行:");
                System.out.println("行号: " + nearestRowNumber);
                System.out.println("温度: " + nearestTemperature + "°C");
                System.out.println("与目标温度的差值: " + minDifference + "°C");

                // 处理整行数据，去除数值的前导零
                String processedRow = processRowWithLeadingZeros(nearestRow);
                System.out.println("整行数据: " + processedRow);
                resut = processedRow;
            } else {
                System.out.println("\n未找到有效的温度数据。");
                resut = "未找到";
            }
            return resut;
        } catch (IOException e) {
            System.err.println("读取文件时发生错误: " + e.getMessage());
            System.err.println("请确保文件路径正确，并且您有访问权限。");
            resut = "读取文件时发生错误";
            return resut;
        }

//        try {
//            System.in.read();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
    /**
     * 处理行数据，去除数值中的前导零
     * @param row 原始行数据
     * @return 处理后的行数据
     */
    private static String processRowWithLeadingZeros(String row) {
        // 首先尝试用逗号分割
        String[] parts = row.trim().split(",");

        // 如果逗号分割后的元素较少，尝试用空格分割
        if (parts.length < 2) {
            parts = Pattern.compile("\\s+").split(row.trim());
        }

        // 处理每个部分，去除数值的前导零
        StringBuilder processedRow = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            String part = parts[i].trim();

            // 对于第一列（温度列），保持原样
            if (i == 0) {
                processedRow.append(part);
            } else {
                // 对于其他列，尝试去除前导零
                processedRow.append(removeLeadingZeros(part));
            }

            // 添加分隔符（如果不是最后一个元素）
            if (i < parts.length - 1) {
                // 使用逗号作为分隔符，保持与原始格式一致
                processedRow.append(",");
            }
        }

        return processedRow.toString();
    }

    /**
     * 去除数字字符串中的前导零
     * @param value 数字字符串
     * @return 去除前导零后的字符串
     */
    private static String removeLeadingZeros(String value) {
        // 检查是否是纯数字
        if (value.matches("\\d+")) {
            // 对于纯数字，去除前导零
            return value.replaceFirst("^0+", "");
        } else if (value.matches("\\d+\\.\\d+")) {
            // 对于小数，只去除整数部分的前导零
            String[] parts = value.split("\\.");
            if (parts.length == 2) {
                String integerPart = parts[0].replaceFirst("^0+", "");
                // 如果整数部分全是零，保留一个零
                if (integerPart.isEmpty()) {
                    integerPart = "0";
                }
                return integerPart + "." + parts[1];
            }
        }
        // 非数字格式，保持原样
        return value;
    }

    /**
     * 表示出力导出数据
     * @return
     * @throws Exception
     */
    @GetMapping("/biaoshiExport")
    public Result biaoshiExport(@RequestParam String grade) throws Exception {

        // 导出数据之前，删除重复等级名称的数据
        String filePath = "D:\\USERS\\01001433\\DESKTOP\\" + grade + ".CSV";

        try {
            Path path = Paths.get(filePath);
            if (Files.exists(path)) {
                Files.delete(path);
                System.out.println("文件已删除: " + filePath);
            } else {
                System.out.println("文件不存在: " + filePath);
            }
        } catch (IOException e) {
            System.err.println("删除文件时出错: " + e.getMessage());
        }

        // Python脚本路径及参数
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\biaoshiExport.py";
        pythnExcute(pythonScript);
        return Result.success();
    }

    /**
     * 保存实验数据100、101
     * @param qaRpaCureInspBeans
     * @return
     */
    @PostMapping("/saveINSPData")
    public Result saveINSPData(@RequestBody QaRpaCureInspBean qaRpaCureInspBeans) {
//        qaRpaCureInspService.save(qaRpaCureInspBeans);
        qaRpaCureInspDao.insert(qaRpaCureInspBeans);
        return Result.success();
    }

    /**
     * 保存实验项数据
     * @param rpaResultBean
     * @return
     */
    @PostMapping("/savePrdQaPlanresult")
    public Result savePrdQaPlanresult(@RequestBody RpaResultBean rpaResultBean){

//        bpr_itemid=353/354/355  /*实验项ID*/
//        bpr_itemname=线膨胀系数(1)/ 线膨胀系数(2)/玻璃化温度
//        bpr_batchno= lot_no   /*实验批号*/
//        bpr_result=机器人计算结果   /*测试结果*/
//        bpr_qa=‘MTA’      /*操作人*/  此处固定位MTA
//        bpr_qadate=’当前时间’    /*操作时间*/
//        bpr_status=’1’        /*0=任务未结束 1=任务结束*/
//        bpr_itmcd=’itm_cd’       /*等级*/
//        bpr_inspseq=’INSP_SEQ’     /*实验项顺序，对应数据库查询字段*/
//        bpr_insptyp=’ INSP_KND_TYP’  /*实验项类型，对应数据库查询字段*/

        PrdBcdQaPlanresult resultc = new PrdBcdQaPlanresult();
        resultc.setBpr_id(UUID.randomUUID().toString());//主键id
        resultc.setBpr_qadate(new Date()); //反馈时间
        resultc.setBpr_status("1");// 子任务状态 0默认 1结束
        // 实验编号
        resultc.setBpr_itemid(rpaResultBean.getBpr_itemid());
        resultc.setBpr_itemname(rpaResultBean.getBpr_itemname());
        resultc.setBpr_batchno(rpaResultBean.getBpr_batchno());
        resultc.setBpr_result(rpaResultBean.getBpr_result());
        resultc.setBpr_qa(rpaResultBean.getBpr_qa());
        // 等级
        resultc.setBpr_itmcd(rpaResultBean.getBpr_itmcd());
        resultc.setBpr_inspseq(rpaResultBean.getBpr_inspseq());
        resultc.setBpr_insptyp(rpaResultBean.getBpr_insptyp());

        // 异常数据
        PrdBcdQaPlanresultEx resultEx = new PrdBcdQaPlanresultEx();
        BeanUtils.copyProperties(resultc,resultEx);
        resultEx.setQuantitative_max(rpaResultBean.getQuantitative_max());
        resultEx.setQuantitative_min(rpaResultBean.getQuantitative_min());

        Qakansa qakansaA = qakansaDao.getByBatchAndItemID(resultc.getBpr_batchno(),resultc.getBpr_itemid());

        String resultS = resultc.getBpr_result();
        Double rd = 1.0;
//        百分比转小数
//        if(resultc.getBpr_result().contains("%")){
//            resultS = resultS.replace("%","");
//            rd = Double.parseDouble(resultS);
//            rd = rd/100.0;
//        }else {
            rd = Double.parseDouble(resultS);
//        }
        handleInsert(qakansaA, rd,resultc,resultEx);
        return Result.success();
    }

    private void handleInsert(Qakansa qakansa, double mesure, PrdBcdQaPlanresult result, PrdBcdQaPlanresultEx resultEx){
        DecimalFormat decimalFormat = new DecimalFormat("0.0");
        System.out.printf("mesure>>>>>>>>>>>>"+mesure);
        BigDecimal mesureDec = new BigDecimal(decimalFormat.format(mesure));
        System.out.printf("min>>>>>>>>>>>>"+qakansa.getQUANTITATIVE_MIN());
        System.out.printf("max>>>>>>>>>>>>"+qakansa.getQUANTITATIVE_MAX());
        if(qakansa.getQUANTITATIVE_MIN() == null && qakansa.getQUANTITATIVE_MAX() != null){
            //1、如果规格参数quantitative_max有数值， 但quantitative_min为null或空，则结果值必须小于等于quantitative_max
            if (mesureDec.compareTo(qakansa.getQUANTITATIVE_MAX()) >0){
                resultExDao.insert(resultEx);
            }else {
                resultDao.insert(result);
            }
        }else if(qakansa.getQUANTITATIVE_MIN() != null && qakansa.getQUANTITATIVE_MAX() == null){
            //2、如果规格参数quantitative_max为null或空， 但quantitative_min有数值，则结果值必须大于等于quantitative_min，否则写入PRD_BCD_QA_PLANRESULT_EX异常记录表
            if (mesureDec.compareTo(qakansa.getQUANTITATIVE_MIN()) <0){
                resultExDao.insert(resultEx);
            }else {
                resultDao.insert(result);
            }
        }else if(qakansa.getQUANTITATIVE_MIN() == null && qakansa.getQUANTITATIVE_MAX() == null){
            resultExDao.insert(resultEx);
        }
        else if(qakansa.getQUANTITATIVE_MIN().compareTo(BigDecimal.valueOf(99999)) == 0 || qakansa.getQUANTITATIVE_MAX().compareTo(BigDecimal.valueOf(99999)) == 0){
            // 4、如果规格参数quantitative_max=99999 或quantitative_min=99999， 则可以录入任意数值
            resultDao.insert(result);
        }else{
            if (mesureDec.compareTo(qakansa.getQUANTITATIVE_MIN())< 0 || mesureDec.compareTo(qakansa.getQUANTITATIVE_MAX()) >0){
                resultExDao.insert(resultEx);
            }else {
                resultDao.insert(result);
            }
        }
    }

    /**
     * 截图OCR识别，判断实验是否结束
     * @return
     * @throws Exception
     */
    @GetMapping("/isExperimentComplete")
    public Result isExperimentComplete() throws Exception{

        //#ra
        String pythonScript = "D:\\curelasto\\code\\curelasto-services\\doc\\ocrExperimentComplete.py";

        ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            process.destroy();
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
                return Result.success(output.toString());
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
                return Result.success("识别失败");
            }

        }

    }
}
